<template>
    <div id="goodDetail">
        <my-head title="商品详情"></my-head>
        <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
            <van-swipe-item>
                <img :src="detail.pic" alt="">
            </van-swipe-item>
            <van-swipe-item>
                <img :src="detail.s_pic" alt="">
            </van-swipe-item>
        </van-swipe>
        <div>
            <p>{{detail.title}}</p>
        </div>
        <van-goods-action>
            <van-goods-action-icon icon="wap-home-o" text="店铺" />
            <van-goods-action-icon icon="cart-o" @click="goCart" :badge="count" text="购物车" />
            <van-goods-action-icon icon="service-o" text="客服" />
            <van-goods-action-button type="primary" @click="addCart" text="加入购物车" />
            <van-goods-action-button type="danger" @click="buy" text="立即购买" />
        </van-goods-action>
    </div>
</template>

<script>
import { getDetail } from '../utils/api'
import myHead from '@/components/head'
import { Toast } from 'vant'
export default {
    name: 'goodDetail',
    components: {
        myHead
    },
    data() { 
        return {
            detail: {},
            count: 0
        }
    },
    created() {
        
        // 获取详情数据
        getDetail(this.$route.query.id).then(res =>{
            // console.log(res)
            this.detail = res
            this.detail.count = 0
            this.detail.checked = false
        })

        this.getGoodNum()
    },
    methods:{
        addCart() {
            if(!localStorage.getItem('token')) {
                this.$router.push({
                    path: '/login',
                    query: {
                        id: this.$route.query.id
                    } 
                })
            } else {
                // 这种触发方法携带参数的方法叫做载荷
                this.$store.commit('changeProducts', this.detail)
                this.getGoodNum()
            }
            
        },

        // 计算购物车商品数量
        getGoodNum() {
            this.count = 0
            var goods = this.$store.state.products
            goods.forEach(item => {
                this.count += item.count
            });
        },

        buy() {
            Toast('购买成功')
        },

        goCart() {
            this.$router.push({
                name: "cart"
            })
        }
    },
}
</script>

<style lang="scss" scoped>
#goodDetail{
    font-size: .3rem;
}
img{
    width: 100%;
}
/deep/ .van-goods-action-button--first, .van-goods-action-button--last {
    border-radius: 0;
    margin: 0;
    height: 1rem;
    font-size: .32rem;
}
</style>